﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using dal.cgm_production_dao;
using Newtonsoft.Json;
using utils;

namespace reader_label_printing
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
            SetPlaceholderText(productionDateTextBox, "yyyy-MM-dd");
            SetPlaceholderText(batchTextBox, "XXXXXXXXXX");
            SetPlaceholderText(snTextBox, "XXXXXXXXX");

            // 绑定事件
            productionDateTextBox.Enter += new EventHandler(productionDateTextBox_Enter);
            productionDateTextBox.Leave += new EventHandler(productionDateTextBox_Leave);

            batchTextBox.Enter += new EventHandler(batchTextBox_Enter);
            batchTextBox.Leave += new EventHandler(batchTextBox_Leave);

            snTextBox.Enter += new EventHandler(snTextBox_Enter);
            snTextBox.Leave += new EventHandler(snTextBox_Leave);

            versionLabel.Text = "v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();


        }
        private void SetPlaceholderText(TextBox textBox, string placeholderText)
        {
            textBox.Text = placeholderText;
            textBox.ForeColor = Color.Gray;
        }
        // 恢复正常文本颜色
        private void RemovePlaceholderText(TextBox textBox)
        {
            textBox.ForeColor = Color.Black;
        }
        // productionDateTextBox 进入事件
        private void productionDateTextBox_Enter(object sender, EventArgs e)
        {
            if (productionDateTextBox.Text == "yyyy-MM-dd")
            {
                productionDateTextBox.Text = "";
                RemovePlaceholderText(productionDateTextBox);
            }
        }
        // productionDateTextBox 离开事件
        private void productionDateTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(productionDateTextBox.Text))
            {
                SetPlaceholderText(productionDateTextBox, "yyyy-MM-dd");
            }
        }
        // batchTextBox 进入事件
        private void batchTextBox_Enter(object sender, EventArgs e)
        {
            if (batchTextBox.Text == "XXXXXXXXXX")
            {
                batchTextBox.Text = "";
                RemovePlaceholderText(batchTextBox);
            }
        }
        // batchTextBox 离开事件
        private void batchTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(batchTextBox.Text))
            {
                SetPlaceholderText(batchTextBox, "XXXXXXXXXX");
            }
        }

        // snTextBox 进入事件
        private void snTextBox_Enter(object sender, EventArgs e)
        {
            if (snTextBox.Text == "XXXXXXXXX")
            {
                snTextBox.Text = "";
                RemovePlaceholderText(snTextBox);
            }
        }
        // snTextBox 离开事件
        private void snTextBox_Leave(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(snTextBox.Text))
            {
                SetPlaceholderText(snTextBox, "XXXXXXXXX");
            }
        }

        /// <summary>
        /// HandleError
        /// </summary>
        /// <param name="message"></param>
        private void HandleError(string message)
        {
            label2.Visible = true;
            label2.ForeColor = Color.Red;
            label2.Text = message;

            AppendLog($"{message}", false);
            ApiLog.Debug($"{message}");

        }


        /// <summary>
        /// AppendLog
        /// </summary>
        /// <param name="message"></param>
        /// <param name="isError"></param>
        private void AppendLog(string message, bool isError)
        {
            // 选择文本颜色
            Color textColor = isError ? Color.Black : Color.Red;

            // 设置光标位置并插入文本
            logRichTextBox.SelectionStart = logRichTextBox.TextLength;
            logRichTextBox.SelectionLength = 0; // 取消任何选择

            logRichTextBox.SelectionColor = textColor; // 设置颜色
            logRichTextBox.AppendText(message + "\n"); // 添加文本
            logRichTextBox.SelectionColor = logRichTextBox.ForeColor; // 恢复默认颜色
            logRichTextBox.ScrollToCaret(); // 自动滚动到最后
        }

        /// <summary>
        /// 清空日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clearLogButton_Click(object sender, EventArgs e)
        {
            logRichTextBox.Clear();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label2.Text = string.Empty;

            DateTime productionDate;

       

            // 检查输入格式是否正确 (yyyy-MM-dd)
            bool isProductionDateValid = DateTime.TryParseExact(productionDateTextBox.Text, "yyyy-MM-dd",
                                                                System.Globalization.CultureInfo.InvariantCulture,
                                                                System.Globalization.DateTimeStyles.None,
                                                                out productionDate);

            // 使用正则表达式检查批号格式：XXXXXXXXXX
            bool isBatchDateValid = System.Text.RegularExpressions.Regex.IsMatch(batchTextBox.Text, @"^\d{2}[A-Z]\d{7}$");

            string snText = snTextBox.Text.Trim();
            // 使用正则表达式检查序列号格式：9位
            bool isSNValid = System.Text.RegularExpressions.Regex.IsMatch(snText, @"^[0-9A-Za-z]{3}\d{6}$");



            if (!isProductionDateValid )
            {
                MessageBox.Show( "请输入正确的日期格式：yyyy-MM-dd", "日期格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
            if (!isBatchDateValid)
            {
                MessageBox.Show( "请输入正确批号", "批号格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
            if (!isSNValid)
            {
                MessageBox.Show( "请输入正确格式序列号", "序列号格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return;
            }
            string snPrefix = snText.Substring(0, 4);
            int startSN = int.Parse(snTextBox.Text.Substring(snText.Length - 5, 5));

            if (startSN == 0)
            {
                MessageBox.Show("请输入正确格式序列号，起始序列号需大于0", "序列号格式错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            string countStr = pageSizeTextBox.Text.Trim();
      
            bool isCountValid =  System.Text.RegularExpressions.Regex.IsMatch(countStr, @"^[0-9]{1,5}$");
            if (!isCountValid)
            {
                MessageBox.Show("请输正确入打印张数", "打印张数错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            int count = int.Parse(pageSizeTextBox.Text.Trim());
            if(count == 0)
            {
                MessageBox.Show("请输正确入打印张数，打印张数不能为0", "打印张数错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (count + startSN - 1 > 99999) {
                MessageBox.Show("请输正确入打印张数,最后一张序列号大于99999", "打印张数错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
             }
            DateTime date;
            string productionDateStr = "";
         
          
            if (DateTime.TryParse(productionDateTextBox.Text.Trim(), out date))
            {
                productionDateStr = date.ToString("yyMMdd");
            }


            try
            {
                for (int i = 0; i < count; i++) {
                    int sn = startSN + i;
                    string SerialCode = snPrefix + sn.ToString().PadLeft(5,'0');
                    var reportPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "reader_label.frx");
                    FastReport.Report report = new FastReport.Report();
                    report.Load(reportPath);

                    var model = new
                    {

                        ProductionDate = productionDateStr,
                        ProductionBatch = batchTextBox.Text,
                        SerialCode = SerialCode,

                    };

                    //刷选可以打印字段特性的模型属性
                    var list = model.GetType().GetProperties();
                    //批量设置打印模板参数值
                    foreach (PropertyInfo pro in list)
                    {
                        var value = pro.GetValue(model, null);
                        //获取参数
                        FastReport.Data.Parameter param = report.Parameters.FindByName(pro.Name);
                        if (param != null)
                        {

                            param.Value = value; //将属性的值赋值给名字相同的报表参数
                        }
                    }
                    report.PrintSettings.Printer = "ZDesigner ZT510-300dpi ZPL"; // 设置默认打印机
                    report.PrintSettings.ShowDialog = false; // 禁止显示打印对话框
                    report.Prepare();

                    // 直接打印报表
                    report.Print();


                    // 释放使用的资源
                    report.Dispose();
                }
                

            }
            catch (Exception ex)
            {
                HandleError(ex.Message);
            }
        }
    }
}
